

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="分享开发的趣事">
  <meta name="author" content="RoseC(陈智豪)">
  <meta name="keywords" content="RoseC的博客,陈智豪,RoseC">
  <meta name="baidu-site-verification" content="code-2LJIrA8S4z" />
  <title>Javascript深浅拷贝问题 - RoseC的博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.5.3/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.1.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"rose-ccc.gitee.io","root":"/","version":"1.8.5","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"copy_btn":true,"image_zoom":{"enable":true},"lazyload":{"enable":true,"onlypost":false},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>RoseC</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/indexImg/index.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Javascript深浅拷贝问题">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-01-07 21:00" pubdate>
        2021年1月7日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      662 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      8
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Javascript深浅拷贝问题</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2021年1月18日 晚上
                
              </p>
            
            <div class="markdown-body">
              <h3 id="想要实现这样一个功能："><a href="#想要实现这样一个功能：" class="headerlink" title="想要实现这样一个功能："></a>想要实现这样一个功能：</h3><p>进入添加数据页面，想添加一些数据，可是写到一半想退出添加数据页面，这时候数据需要回退为之前的旧数据</p>
<p>代码逻辑如下：</p>
<pre><code class="hljs bash"><span class="hljs-comment"># 原数据</span>
<span class="hljs-built_in">let</span> info = &#123;
	name: <span class="hljs-string">&quot;Mike&quot;</span>,
	age: 15
&#125;

<span class="hljs-comment"># 更改</span>
<span class="hljs-comment"># 1.保存旧数据</span>
<span class="hljs-built_in">let</span> <span class="hljs-built_in">history</span> = info
<span class="hljs-comment"># 2.更改新数据</span>
<span class="hljs-built_in">let</span> info = &#123;
	name: <span class="hljs-string">&quot;new name&quot;</span>,
	age: <span class="hljs-string">&quot;new age&quot;</span>
&#125;
<span class="hljs-comment"># 3.退出，将数据指向history</span>
<span class="hljs-built_in">let</span> info = <span class="hljs-built_in">history</span>

<span class="hljs-comment"># 输出现在的数据</span>
console.log(info)  <span class="hljs-comment"># &#123;name:&quot;new name&quot;,age:&quot;new age&quot;&#125;</span></code></pre>
<h3 id="这时候会发现这样的问题："><a href="#这时候会发现这样的问题：" class="headerlink" title="这时候会发现这样的问题："></a>这时候会发现这样的问题：</h3><p>即使在更改数据前，将旧数据(info)指向一个中间变量(history)，在更改旧数据(info)后，这个中间变量(history)也跟随改变了，并没有起到保存的作用</p>
<h2 id="问题的原因"><a href="#问题的原因" class="headerlink" title="问题的原因"></a>问题的原因</h2><p>经过上面这么长的铺垫，终于可以进入我们的正题，也是出现上面问题的原因：</p>
<h3 id="javascript变量"><a href="#javascript变量" class="headerlink" title="javascript变量"></a>javascript变量</h3><p>javascript的变量有两种：<br>1.原始值：简单的数据，按值访问<br>2.引用值：多个数据构成的对象，按引用访问</p>
<p>复制原始值时，就是将值复制一份，例如：</p>
<pre><code class="hljs bash"><span class="hljs-built_in">let</span> a = 123
<span class="hljs-built_in">let</span> b = a
console.log(a,b) <span class="hljs-comment"># 123,123</span></code></pre>
<p><img src="/2021/01/07/Javascript%E6%B7%B1%E6%B5%85%E6%8B%B7%E8%B4%9D%E9%97%AE%E9%A2%98/p1.png" srcset="/img/loading.gif" alt="原始值复制"></p>
<p>复制引用值时，是将值的引用指向新的变量，数据堆中并没有新的数据出现，例如：</p>
<pre><code class="hljs bash"><span class="hljs-built_in">let</span> a = &#123;
	name: 123,
	age: 456
&#125;
<span class="hljs-built_in">let</span> b = a
console.log(a,b) <span class="hljs-comment">#&#123;name: 123, age: 456&#125;，&#123;name: 123, age: 456&#125;</span>
a.name = 789
console.log(a,b) <span class="hljs-comment">#&#123;name: 789, age: 456&#125;，&#123;name: 789, age: 456&#125;</span></code></pre>
<p>因为更改的都是数据堆里的值，所以指向该对象的变量数据都会随之改变<br><img src="/2021/01/07/Javascript%E6%B7%B1%E6%B5%85%E6%8B%B7%E8%B4%9D%E9%97%AE%E9%A2%98/p2.png" srcset="/img/loading.gif" alt="引用值复制"></p>
<h2 id="解决办法"><a href="#解决办法" class="headerlink" title="解决办法"></a>解决办法</h2><p>这里我们可以使用深拷贝的方法来改变引用值的复制，原理如下：<br>将对象转换为json字符串形式（String类型在Javascript中是原始值），再将该值赋值给新变量，再将该变量转换为原生js对象</p>
<pre><code class="hljs bash">deepClone(obj)&#123;
	<span class="hljs-built_in">let</span> _tmp = JSON.stringify(obj); //将对象转换为json字符串形式
	<span class="hljs-built_in">let</span> result = JSON.parse(_tmp); //将转换而来的字符串转换为原生js对象
	<span class="hljs-built_in">return</span> result;
&#125;
<span class="hljs-built_in">let</span> a = &#123;
	name: 123,
	age: 456
&#125;
<span class="hljs-built_in">let</span> b = deepClone(a)
console.log(a,b) <span class="hljs-comment">#&#123;name: 123, age: 456&#125;，&#123;name: 123, age: 456&#125;</span>
a.name = 789
console.log(a,b) <span class="hljs-comment">#&#123;name: 789, age: 456&#125;，&#123;name: 123, age: 456&#125;</span></code></pre>
<p>深拷贝的方法还有很多，这个是比较投机取巧的方法，使用这样的办法，可以在数据堆中新增一个Object，解决上面问题，不过在数据量较大时，容易发生栈溢出，不过在数据量较小时，推荐使用</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%89%8D%E7%AB%AF/">前端</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Javascript/">Javascript</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/02/06/Express+Multer%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Express+Multer图片上传</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/12/05/%E6%97%A0%E7%BC%9D%E8%BD%AE%E6%92%AD%E5%9B%BE/">
                        <span class="hidden-mobile">无缝轮播图</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":200})
    NProgress.start()
    document.addEventListener('DOMContentLoaded', function() {
      window.NProgress && window.NProgress.inc();
    })
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.staticfile.org/jquery/3.5.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.5.3/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script  src="https://cdn.staticfile.org/tocbot/4.12.0/tocbot.min.js" ></script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
